/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.getTimer;
	import mx.containers.HBox;
	import mx.controls.Button;
	import mx.controls.sliderClasses.Slider;
	import mx.events.SliderEvent;

	[Event(name="change", type="flash.events.Event")]
	public class PlayerBase extends HBox
	{

		public var pauseButton:Button;

		public var playButton:Button;

		public var slider:Slider;

		private var _playHead:Number;

		private var _playTime:uint;

		private var _value:Number;

		public function PlayerBase()
		{
			_value = 0;
		}

		public function get value():Number
		{
			return _value / 1000;
		}

		override protected function createChildren():void
		{
			super.createChildren();

			pauseButton.addEventListener(MouseEvent.CLICK, pauseHandler);
			playButton.addEventListener(MouseEvent.CLICK, playHandler);
			slider.addEventListener(SliderEvent.CHANGE, changeHandler);
		}

		private function changeHandler(e:SliderEvent):void
		{
			_value = e.value;
			dispatchEvent(new Event(Event.CHANGE));
		}

		private function enterFrameHandler(e:Event):void
		{
			slider.value = _playHead + (getTimer() - _playTime);
			if (slider.value >= slider.maximum)
			{
				pauseHandler(null);
			}

			_value = slider.value;
			dispatchEvent(new Event(Event.CHANGE));
		}

		private function pauseHandler(e:MouseEvent):void
		{
			playButton.visible = playButton.includeInLayout = true;
			pauseButton.visible = pauseButton.includeInLayout = false;
			slider.mouseEnabled = slider.mouseChildren = true;

			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}

		private function playHandler(e:MouseEvent):void
		{
			playButton.visible = playButton.includeInLayout = false;
			pauseButton.visible = pauseButton.includeInLayout = true;
			slider.mouseEnabled = slider.mouseChildren = false;

			if (slider.value >= slider.maximum)
			{
				slider.value = 0;
			}

			_playTime = getTimer();
			_playHead = slider.value;
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
	}
}
